var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// const mysql=require("mysql");
var adminRouter = require('./routes/admin');
var chargeStationRouter = require('./routes/chargeStation');
var orderRouter = require('./routes/order');
var loveStationRouter = require('./routes/loveStation');
var uploadRouter = require('./routes/upload');

// 共享连接池
// let mysqlpool = require("./model/connect");
/* mysqlpool.connect((err)=>{
  if(err) throw err;
  console.log("数据库连接成功");
}) */

var app = express();

//设置模板引擎 设置模板路径为当前项目目录下 views/文件夹
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
//设置express中间件解析json数据 application/json
app.use(express.json());
//设置express中间件来解析post传值
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//设置静态文件路径在public文件夹
app.use(express.static(path.join(__dirname, 'public')));
//运行所有请求跨域
app.use( function( req,res,next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method' );
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE');
  res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE');
  next();
})


//后台路由模块 /admin/****都是后台.
app.use("/admin",adminRouter)
app.use('/chargeStation', chargeStationRouter);
app.use('/order', orderRouter);
app.use('/love', loveStationRouter);
app.use('/upload',uploadRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
